package com.netdisk.controller;

import com.netdisk.dto.FileDTO;
import com.netdisk.service.FileService;
import com.netdisk.service.TrashService;
import com.netdisk.service.UserActivityService;
import com.netdisk.vo.PageResult;
import com.netdisk.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 回收站控制器
 */
@Api(tags = "回收站管理")
@RestController
@RequestMapping("/trash")
public class TrashController {

    @Autowired
    private TrashService trashService;
    
    @Autowired
    private FileService fileService;
    
    @Autowired
    private UserActivityService userActivityService;

    @ApiOperation("获取回收站文件列表")
    @GetMapping("/list")
    public Result<PageResult<FileDTO>> listTrashFiles(
            @ApiParam(value = "用户ID", required = true) @RequestParam("userId") Integer userId,
            @ApiParam(value = "页码", defaultValue = "1") @RequestParam(value = "page", defaultValue = "1") Integer page,
            @ApiParam(value = "每页大小", defaultValue = "10") @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @ApiParam(value = "搜索关键词", required = false) @RequestParam(value = "query", required = false, defaultValue = "") String query) {
        PageResult<FileDTO> pageResult = trashService.listTrashFiles(userId, page, pageSize, query);
        return Result.success(pageResult);
    }

    @ApiOperation("恢复文件")
    @PostMapping("/restore")
    public Result<Void> restoreFile(
            @ApiParam(value = "文件ID", required = true) @RequestParam("fileId") Integer fileId,
            @ApiParam(value = "用户ID", required = true) @RequestParam("userId") Integer userId,
            HttpServletRequest request) {
        
        try {
            // 从回收站获取文件信息，而不是从fileService（因为文件已经在回收站中）
            FileDTO fileDTO = trashService.getTrashFileInfo(fileId, userId);
            
            if (fileDTO == null) {
                return Result.error("文件不在回收站中");
            }
            
            boolean result = trashService.restoreFile(fileId, userId);
            
            if (result) {
                // 记录恢复文件活动
                try {
                    userActivityService.recordActivity(
                        userId, 
                        fileId, 
                        fileDTO.getName(), 
                        "restore", 
                        "从回收站恢复了文件 \"" + fileDTO.getName() + "\"",
                        request.getRemoteAddr(),
                        request.getHeader("User-Agent")
                    );
                } catch (Exception e) {
                    // 记录活动失败，但不影响功能
                    System.err.println("Failed to record activity: " + e.getMessage());
                }
                
                return Result.success("恢复成功", null);
            } else {
                return Result.error("恢复失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("恢复文件出错: " + e.getMessage());
        }
    }

    @ApiOperation("彻底删除文件")
    @DeleteMapping("/delete")
    public Result<Void> deleteFileCompletely(
            @ApiParam(value = "文件ID", required = true) @RequestParam("fileId") Integer fileId,
            @ApiParam(value = "用户ID", required = true) @RequestParam("userId") Integer userId,
            HttpServletRequest request) {
        
        try {
            // 从回收站获取文件信息
            FileDTO fileDTO = trashService.getTrashFileInfo(fileId, userId);
            
            if (fileDTO == null) {
                return Result.error("文件不在回收站中");
            }
            
            String fileName = fileDTO.getName();
            boolean result = trashService.deleteFileCompletely(fileId, userId);
            
            if (result) {
                // 记录彻底删除文件活动
                try {
                    userActivityService.recordActivity(
                        userId, 
                        fileId, 
                        fileName, 
                        "delete_permanently", 
                        "彻底删除了文件 \"" + fileName + "\"",
                        request.getRemoteAddr(),
                        request.getHeader("User-Agent")
                    );
                } catch (Exception e) {
                    // 记录活动失败，但不影响功能
                    System.err.println("Failed to record activity: " + e.getMessage());
                }
                
                return Result.success("删除成功", null);
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("彻底删除文件出错: " + e.getMessage());
        }
    }

    @ApiOperation("清空回收站")
    @DeleteMapping("/clear")
    public Result<Void> clearTrash(
            @ApiParam(value = "用户ID", required = true) @RequestParam("userId") Integer userId,
            HttpServletRequest request) {
        
        boolean result = trashService.clearTrash(userId);
        
        if (result) {
            // 记录清空回收站活动
            try {
                userActivityService.recordActivity(
                    userId, 
                    null, 
                    null, 
                    "clear_trash", 
                    "清空了回收站",
                    request.getRemoteAddr(),
                    request.getHeader("User-Agent")
                );
            } catch (Exception e) {
                // 记录活动失败，但不影响功能
                System.err.println("Failed to record activity: " + e.getMessage());
            }
        }
        
        return result ? Result.success("清空成功", null) : Result.error("清空失败");
    }
} 